package com.bytecodezz.app.base.toolset.security

import java.math.BigInteger
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import kotlin.experimental.and

/**
 * @author: bytecodezz
 * @version: 1.0
 * @time: 2021/9/6 17:45
 * @package: com.bytecodezz.app.base.toolset.security
 *
 * @description:
 *
 */
object MD5Tools {
    private val ALGORITHM = "MD5"
    private val HEX_DIGITS = charArrayOf(
        '0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    )

    /**
     * encode By MD5
     *
     * @param str
     * @return String
     */
    fun encode(str: String?): String? {
        return if (str == null) {
            null
        } else try {
            val messageDigest = MessageDigest.getInstance(ALGORITHM)
            messageDigest.update(str.toByteArray())
            getFormattedText(messageDigest.digest())
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    /**
     * Takes the raw bytes from the digest and formats them correct.
     *
     * @param bytes
     * the raw bytes from the digest.
     * @return the formatted bytes.
     */
    private fun getFormattedText(bytes: ByteArray): String? {
        val len = bytes.size
        val buf = StringBuilder(len * 2)
        // 把密文转换成十六进制的字符串形式
        for (j in 0 until len) {
            buf.append(HEX_DIGITS[bytes[j].toInt() shr 4 and 0x0f])
            buf.append(HEX_DIGITS[bytes[j].toInt() and 0x0f])
        }
        return buf.toString()
    }
}
